package com.study.netty.echodemo;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import java.net.InetSocketAddress;

/**
 * Created by tan on 2017/7/17.
 */
public class EchoServer {
	private int port;

	public EchoServer(int port) {
		this.port = port;
	}


	public static void main(String[] args) throws InterruptedException {
		new EchoServer(82).start();
	}

	public void start() throws InterruptedException {
		EchoServerHandler serverHandler = new EchoServerHandler();
		//创建一个ServerBootstrap 来引导和绑定服务器
		ServerBootstrap bootstrap = new ServerBootstrap();
		//创建一个EventLoopGroup实例 来进行事件处理。 如接受新连接以及读/写数据
		EventLoopGroup group = new NioEventLoopGroup();
		try {
			bootstrap.group(group).channel(NioServerSocketChannel.class)
					.localAddress(new InetSocketAddress(port))//绑定
					.childHandler(new ChannelInitializer<SocketChannel>() {//使用一个EchoServerHandler初始化每一个新的channel
						@Override
						protected void initChannel(SocketChannel ch) throws Exception {
							ch.pipeline().addLast(serverHandler);
						}
					});

			//绑定服务器
			ChannelFuture future = bootstrap.bind().sync();
			future.channel().closeFuture().sync();
		} finally {
			group.shutdownGracefully().sync();
		}

	}
}
